import { Module } from 'vuex'
import router from '@/router/router'
import type { IloginState } from './types'
import type { IRootState } from '../types'
import type { IAccount } from '@/service/login/type'
import Localcache from '@/utils/cache'
import { mapMenusToRoutes, mapMenusToPermission } from '@/utils/map-menus'
import {
  accountLoginRequest,
  usersLoginRequest,
  roleLoginRequest
} from '@/service/login/login'
const LoginModule: Module<IloginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userinfo: {},
      userMenus: {},
      permission: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeInfo(state, userInfo) {
      state.userinfo = userInfo
    },
    changerole(state, userMenus) {
      state.userMenus = userMenus
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      const permission = mapMenusToPermission(userMenus)
      state.permission = permission
    }
  },
  actions: {
    async accountLoginActive({ commit }, payload: IAccount) {
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeToken', token)
      Localcache.setcache('token', token)

      //请求用户数据
      const usersLoginResult = await usersLoginRequest(id)
      const userInfo = usersLoginResult.data
      commit('changeInfo', userInfo)
      Localcache.setcache('userInfo', userInfo)
      console.log(userInfo)

      //请求用户菜单
      const roleLoginResult = await roleLoginRequest(userInfo.role.id)
      const roleLogin = roleLoginResult.data
      commit('changerole', roleLogin)
      Localcache.setcache('userMenus', roleLogin)
      console.log(roleLogin)

      router.replace('/main')
    },
    loadLoaclLogin({ commit }) {
      const token = Localcache.getcache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userinfo = Localcache.getcache('userInfo')
      if (userinfo) {
        commit('changeInfo', userinfo)
      }
      const userMenus = Localcache.getcache('userMenus')
      if (userMenus) {
        commit('changerole', userMenus)
      }
    }
  }
}

export default LoginModule
